package com.xjoyt.pay.operater.services;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xjoyt.pay.abstracts.AbstractService;
import com.xjoyt.pay.commons.ObjectUtils;
import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.dto.PageParam;
import com.xjoyt.pay.dto.PageResult;
import com.xjoyt.pay.master.interfaces.CompanyContract;
import com.xjoyt.pay.master.po.Company;
import com.xjoyt.pay.operater.auth.params.AccountUserParam;
import com.xjoyt.pay.operater.auth.params.UserPageParam;
import com.xjoyt.pay.operater.auth.po.AccountUser;
import com.xjoyt.pay.operater.auth.po.UserRole;
import com.xjoyt.pay.operater.repository.UserRepository;
import com.xjoyt.pay.operater.repository.UserRoleRepository;
import com.xjoyt.pay.params.ChangePasswordParam;
import com.xjoyt.pay.params.LoginParam;

@Service
public class UserService extends AbstractService {

	@Autowired
	private UserRepository repository;

	@Autowired
	private CompanyContract companyContract;

	@Autowired
	private UserRoleRepository userRoleRepository;

	public AccountUser get(String id) {
		return repository.findOne(id);
	}

	public PageResult<AccountUser> loadPage(PageParam<UserPageParam> param) {
		return repository.loadPage(param);
	}

	public ExecuteResult<AccountUser> save(AccountUserParam accountUserParam) {
		if (StringUtils.isBlank(accountUserParam.phone)) {
			return ExecuteResult.fail("账号和手机号不能为空");
		}

		AccountUser user = repository.findOneByPhone(accountUserParam.phone);
		if (user != null) {
			return ExecuteResult.fail("账号或手机号重复");
		}
		
		AccountUser accountUser = new AccountUser();
		ObjectUtils.fieldCopy(accountUserParam, accountUser);
		if (accountUser.addedDate == null)
			accountUser.addedDate = new Date();
		
//		if (accountUser.id==0) {
//			userRoleRepository.findAllByUserId(accountUser.id+"").forEach(item -> userRoleRepository.delete(item));
//		}
		List<UserRole> userRoleList = accountUser.userRoleList;
		accountUser.userRoleList = null;
		accountUser = repository.save(accountUser);
		if (CollectionUtils.isNotEmpty(userRoleList)) {
			for (UserRole item : userRoleList) {
				item.id = 0;
				item.user = accountUser;
				userRoleRepository.save(item);
			}
		}
		return ExecuteResult.ok(accountUser);
	}

	public ExecuteResult<?> delete(String id) {
		repository.delete(id);
		return ExecuteResult.ok();
	}

	public ExecuteResult<AccountUser> getByAccount(LoginParam param) {
		if (StringUtils.isBlank(param.password)) {
			return ExecuteResult.fail("请输入密码");
		}

		AccountUser entity = repository.findOneByAccountOrPhone(param.account, param.account);
		if (entity == null) {
			return ExecuteResult.fail("用户不存在");
		}
		
		if (StringUtils.isBlank(entity.password)) {
			if ("123456".equals(param.password)) {
				return ExecuteResult.ok(entity);
			}
			return ExecuteResult.fail("密码错误");
		}
		String pwd = StringUtils.isBlank(entity.salt) ? param.password : (param.password + entity.salt);
		String md5Hex = DigestUtils.md5Hex(pwd);
		if (!md5Hex.equals(entity.password)) {
			return ExecuteResult.fail("密码错误");
		}

		if (!BooleanUtils.isTrue(entity.enabled)) {
			return ExecuteResult.fail("账号已停用");
		}

		if (StringUtils.isBlank(entity.companyId)) {
			return ExecuteResult.fail("机构不存在");
		}
		Company company = companyContract.get(entity.companyId);
		if (company == null)
			return ExecuteResult.fail("无法获取机构");
		if (!BooleanUtils.isTrue(company.enabled)) {
			return ExecuteResult.fail("机构已被停用");
		}

		entity.lastLoginTime = new Date();
		repository.save(entity);
		return ExecuteResult.ok(entity);
	}

	public ExecuteResult<?> changePassword(ChangePasswordParam param) {
		if (StringUtils.isBlank(param.id)) {
			return ExecuteResult.fail("ID不能为空");
		}

		if (StringUtils.isBlank(param.oldPassword) || StringUtils.isBlank(param.newPassword)
				|| StringUtils.isBlank(param.password)) {
			return ExecuteResult.fail("密码不能为空");
		}

		if (!param.password.equals(param.newPassword)) {
			return ExecuteResult.fail("两次密码不一致");
		}

		AccountUser entity = repository.findOne(param.id);
		if (entity == null) {
			return ExecuteResult.fail("用户不存在");
		}
		if (StringUtils.isBlank(entity.password)) {
			if (!"123456".equals(param.oldPassword))
				return ExecuteResult.fail("密码错误");
		} else {
			String pwd = StringUtils.isBlank(entity.salt) ? param.password : (param.password + entity.salt);
			String md5Hex = DigestUtils.md5Hex(pwd);
			if (!md5Hex.equals(entity.password)) {
				return ExecuteResult.fail("密码错误");
			}
		}

		entity.salt = UUID.randomUUID().toString().substring(0, 4).toUpperCase();
		entity.password = DigestUtils.md5Hex(param.password + entity.salt);
		repository.save(entity);
		return ExecuteResult.ok();
	}

	public AccountUser getUserByUsername(String userName) {
		return repository.getUserByUserName(userName);
	}

	public AccountUser getUserByPhone(String phone) {
		return repository.getUserByPhone(phone);
	}
}
